//
//  JQFXHMineViewController.swift
//  jiuzhoudai
//
//  Created by zhaochengfeng on 2025/7/8.
//

import UIKit

class JQFXHMineViewController: HJYJBaseViewController {
    
    var jqfxhTitlesjjArr = ["还款详情", "注册协议", "隐私政策", "帮助与反馈", "修改密码", "退出登录", "注销账户"]

    override func viewDidLoad() {
        super.viewDidLoad()
        jqfxhIsNavBarjjHidden = true
        
        self.jqfxhSetkkUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.jqfxhUpdateLginStatus()
        self.jqfxhUpdateServicettInfo()
    }
    
    func jqfxhUpdateLginStatus() -> Void {
        if let user = JQFXHNetworkManager.shared.jqfxhCurrentUser {
            let leadingStr = user.mobile.prefix(3)
            let endStr = user.mobile.suffix(4)
            self.jqfxhPhoneppBtn.setTitle(leadingStr + "****" + endStr, for: .normal)
        }else {
            self.jqfxhPhoneppBtn.setTitle("点击登录 >", for: .normal)
        }
        
    }
    
    
    func jqfxhSetkkUI() -> Void {
        self.view.backgroundColor = UIColor.jqfxhBigViewBgccGray
        self.view.addSubview(jqfxhllScrollview)
        jqfxhllScrollview.addSubview(jqfxhContentmmView)
        jqfxhllScrollview.snp.makeConstraints { make in
            make.edges.equalTo(self.view)
        }
        jqfxhContentmmView.snp.makeConstraints { make in
            make.top.bottom.equalTo(jqfxhllScrollview)
            make.left.right.equalTo(self.view)
        }
        
        jqfxhContentmmView.addSubview(jqfxhBgnnImage)
        jqfxhBgnnImage.snp.makeConstraints { make in
            make.left.right.top.equalTo(jqfxhContentmmView)

        }
        
        jqfxhContentmmView.addSubview(jqfxhAvtarooImg)
        jqfxhAvtarooImg.snp.makeConstraints { make in
            make.left.equalTo(17)
            make.top.equalTo(UIApplication.shared.jqfxhSafeAreaInsets.top+40)
            make.width.height.equalTo(52)
        }
        
        jqfxhContentmmView.addSubview(jqfxhKessfuBtn)
        jqfxhKessfuBtn.snp.makeConstraints { make in
            make.right.equalTo(jqfxhContentmmView).offset(-20)
            make.centerY.equalTo(jqfxhAvtarooImg).offset(-10)
        }
        
        
        jqfxhContentmmView.addSubview(jqfxhPhoneppBtn)
        jqfxhPhoneppBtn.snp.makeConstraints { make in
            make.left.equalTo(jqfxhAvtarooImg.snp.right).offset(10)
            make.centerY.equalTo(jqfxhAvtarooImg).offset(-10)
        }
        jqfxhContentmmView.addSubview(jqfxhNavSubqqTitleLabel)
        jqfxhNavSubqqTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(jqfxhPhoneppBtn)
            make.top.equalTo(jqfxhPhoneppBtn.snp.bottom).offset(3)
        }
        
        jqfxhContentmmView.addSubview(jafxhEdurrCardImg)
        jafxhEdurrCardImg.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentmmView).offset(16)
            make.centerX.equalTo(jqfxhContentmmView)
            make.top.equalTo(jqfxhAvtarooImg.snp.bottom).offset(46)
            make.height.equalTo(120)
        }
        

        
        jafxhEdurrCardImg.addSubview(jqfxhYugussCountTitle)
        jqfxhYugussCountTitle.snp.makeConstraints { make in
            make.left.top.equalTo(jafxhEdurrCardImg).offset(20)
        }
        jafxhEdurrCardImg.addSubview(jqfxhCountTttitle)
        jqfxhCountTttitle.snp.makeConstraints { make in
            make.left.equalTo(jqfxhYugussCountTitle)
            make.top.equalTo(jqfxhYugussCountTitle.snp.bottom).offset(3)
        }
        
        
        jqfxhContentmmView.addSubview(jqfxhListuuBg)
        jqfxhListuuBg.snp.makeConstraints { make in
            make.left.right.equalTo(jafxhEdurrCardImg)
            make.top.equalTo(jafxhEdurrCardImg.snp.bottom).offset(20)
            make.height.equalTo(297)
        }
        jqfxhListuuBg.addSubview(jqfxhMyGongvvTitleLabel)
        jqfxhMyGongvvTitleLabel.snp.makeConstraints { make in
            make.left.top.equalTo(jqfxhListuuBg).offset(15)
        }
        
        
        jqfxhContentmmView.addSubview(jqfxhBeianwwLabel)
        jqfxhBeianwwLabel.snp.makeConstraints { make in
            make.centerX.equalTo(jqfxhContentmmView)
            make.top.equalTo(jqfxhListuuBg.snp.bottom).offset(20)
            make.bottom.equalTo(jqfxhContentmmView).offset(-50)
        }
        
        for index in 0..<jqfxhTitlesjjArr.count {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "jqfxh_mine_item_" + String(index)), for: .normal)
            // 设置按钮的frame
            let itemWidth = (jqfxhScreenWidth-32)/3

            if index < 3 {
                button.frame = CGRect(x: CGFloat(index)*itemWidth, y: 50, width: itemWidth, height: 60)
            }else if index < 6 {
                button.frame = CGRect(x: CGFloat((index-3))*itemWidth, y: 130, width: itemWidth, height: 60)
            }else {
                button.frame = CGRect(x: CGFloat((index-6))*itemWidth, y: 210, width: itemWidth, height: 60)
            }
            button.tag = index
            button.addTarget(self, action: #selector(listBtnClick(sender:)), for: .touchUpInside)
            // 添加到父视图
            jqfxhListuuBg.addSubview(button)
        }
        
        
    }
    @objc func jqfxhUpdateServicettInfo() {
        let provider = JQFXHNetworkManager.shared.provider
        JQFXHNetworkManager.shared.jqfxhRequest(provider: provider, target: .jqfxhServicehhInfo, type:JQFXHServerddInfoData.self) { result in
            switch result {
            case.success(let serverInfo):
                if serverInfo.app_config.partner_id != JQFXHNetworkManager.shared.partnerId {
                    JQFXHNetworkManager.shared.jqfxhCurrentUser = nil
                    JQFXHNetworkManager.shared.currentServerInfo = serverInfo
                }
                self.jqfxhUpdateLginStatus()
            case .failure(let error):
                print(error)
            }
        }
    }
    
    func jqfxhTologinuuVC() -> Void {
        JQFXHHUD.jqfxhShowssLoading()
        let provider = JQFXHNetworkManager.shared.provider
        JQFXHNetworkManager.shared.jqfxhRequest(provider: provider, target: .jqfxhServicehhInfo, type:JQFXHServerddInfoData.self) { result in
            JQFXHHUD.jqfxhHttidden()
            switch result {
            case.success(let serverInfo):
                JQFXHNetworkManager.shared.currentServerInfo = serverInfo
                let loginvc = JQFXHLoginViewController.init()
                self.navigationController?.pushViewController(loginvc, animated: true)
            case .failure(let error):
                print(error)
            }
        }
        
    }

    
    @objc func listBtnClick(sender: UIButton) {
        let string = self.jqfxhTitlesjjArr[sender.tag]
        if string == "隐私政策" {
            let web = JQFXHWebViewController(jqfxhUrlccString: JQFXHCompanyMessage.jqfxhPrivacyPolicyURL, jqfxhTitle: string)
            self.navigationController?.present(web, animated: true)
        }else if string == "注册协议" {
            let web = JQFXHWebViewController(jqfxhUrlccString: JQFXHCompanyMessage.jqfxhUserAgreementURL, jqfxhTitle: string)
            self.navigationController?.present(web, animated: true)
        }else {
            if JQFXHNetworkManager.shared.jqfxhCurrentUser == nil {
                self.jqfxhTologinuuVC()
            }else {
                if string == "修改密码" {
                    let secvc = JQFXHSecrectSettingViewController()
                    self.navigationController?.pushViewController(secvc, animated: true)
                }else if string == "帮助与反馈" {
                    let feedbackvc = JQFXHFeedbackViewController()
                    self.navigationController?.pushViewController(feedbackvc, animated: true)
                }else if string == "退出登录" {
                    self.showLogoutAlert(on: self) {
                        JQFXHNetworkManager.shared.jqfxhCurrentUser = nil
                        self.jqfxhUpdateLginStatus()
                    }
                }else if string == "注销账户" {
                    self.showLogoffAlert(on: self) {
                        self.jqfxhLogppoff()
                    }
                }else if string == "还款详情" {
                    if JQFXHNetworkManager.shared.hasApply {
                        JQFXHHUD.jqfxhShowxxText("正在审核中 请耐心等待")
                    }else {
                        JQFXHHUD.jqfxhShowxxText("暂无申请")

                    }
                }
            }

        }
    }
    
    func toKnowledge() -> Void {
        let knowledge = JQFXHLoanKnowlagemmViewController.init()
        self.navigationController?.pushViewController(knowledge, animated: true)
    }
    

    func jqfxhLogppoff() -> Void {
        JQFXHHUD.jqfxhShowssLoading()

        let provider = JQFXHNetworkManager.shared.provider
        if JQFXHNetworkManager.shared.partnerId == 1 {
            JQFXHNetworkManager.shared.jqfxhRequest(provider: provider, target: .jqfxhLogppoff) { result in
                JQFXHHUD.jqfxhHttidden()
                switch result {
                case .success(_):
                    self.jqfxhLogppoffSuccess()
                case .failure(let error):
                    print(error)
                }
            }
        }else {
            JQFXHNetworkManager.shared.jqfxhRequest(provider: provider, target: .jqfxhThirdLogqqoff) { result in
                JQFXHHUD.jqfxhHttidden()
                switch result {
                case .success(_):
                    self.jqfxhLogppoffSuccess()
                case .failure(let error):
                    print(error)
                }
            }
        }
    }
    
   
    func showLogoutAlert(on viewController: UIViewController, logoutAction: @escaping () -> Void) {
        let alert = UIAlertController(
            title: "确定退出登录？",
            message: "",
            preferredStyle: .alert
        )

        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let confirmAction = UIAlertAction(title: "确定", style: .destructive) { _ in
            logoutAction()
        }

        alert.addAction(cancelAction)
        alert.addAction(confirmAction)

        viewController.present(alert, animated: true, completion: nil)
    }
    
    func showLogoffAlert(on viewController: UIViewController, logoutAction: @escaping () -> Void) {
        let alert = UIAlertController(
            title: "确定退出注销账户？",
            message: "",
            preferredStyle: .alert
        )

        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let confirmAction = UIAlertAction(title: "确定", style: .destructive) { _ in
            logoutAction()
        }

        alert.addAction(cancelAction)
        alert.addAction(confirmAction)

        viewController.present(alert, animated: true, completion: nil)
    }

    
    @objc func loginBtnClick() {
        if JQFXHNetworkManager.shared.jqfxhCurrentUser == nil {
            self.jqfxhTologinuuVC()
        }
    }
    
    @objc func jqfxhKessfuBtnClick() {
        let alert = UIAlertController(title: "确认拨打",
                                      message: "是否拨打 \(158893267935) ？",
                                      preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        alert.addAction(UIAlertAction(title: "呼叫", style: .destructive, handler: { _ in
            self.jqfxhCattll("158893267935")
        }))
        present(alert, animated: true)
    }
    
    private func jqfxhCattll(_ number: String) {
            let cleaned = number.filter { $0.isNumber || $0 == "+" }
            if let url = URL(string: "tel://\(cleaned)"),
               UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url)
            } else {
                let errorAlert = UIAlertController(
                    title: "无法拨号",
                    message: "您的设备不支持电话功能",
                    preferredStyle: .alert
                )
                errorAlert.addAction(UIAlertAction(title: "确定", style: .default))
                present(errorAlert, animated: true)
            }
        }
    
   
    
    func jqfxhLogppoffSuccess() {
        JQFXHHUD.jqfxhShowvvSuccess("注销成功")
        JQFXHNetworkManager.shared.jqfxhCurrentUser = nil
        self.jqfxhUpdateLginStatus()
    }
    
    
    
    
    lazy var jqfxhContentmmView : UIView = {
        let jqfxhContentmmView = UIView()
        
        return jqfxhContentmmView
    }()
    lazy var jqfxhllScrollview : UIScrollView = {
        let jqfxhllScrollview = UIScrollView(frame: CGRectMake(0, 0, jqfxhScreenWidth, jqfxhScreenHeight))
        if #available(iOS 11.0, *) {
            jqfxhllScrollview.contentInsetAdjustmentBehavior = .never
        } else {
        }
        return jqfxhllScrollview
    }()
   
    lazy var jqfxhAvtarooImg : UIImageView = {
        let jqfxhAvtarooImg = UIImageView()
        jqfxhAvtarooImg.image = UIImage(named: "jqfxh_handsome_avtar")
        return jqfxhAvtarooImg
    }()
    
    lazy var jqfxhPhoneppBtn : UIButton = {
        let jqfxhPhoneppBtn = UIButton(type: .custom)
        jqfxhPhoneppBtn.setTitle("点击登录 >", for: .normal)
        jqfxhPhoneppBtn.setTitleColor(UIColor.white, for: .normal)
        jqfxhPhoneppBtn.titleLabel?.font = UIFont.jqfxhRegular18
        jqfxhPhoneppBtn.addTarget(self, action: #selector(loginBtnClick), for: .touchUpInside)
        return jqfxhPhoneppBtn
    }()
    
    lazy var jqfxhKessfuBtn : UIButton = {
        let jqfxhKessfuBtn = UIButton(type: .custom)
        jqfxhKessfuBtn.setTitle("客服", for: .normal)
        jqfxhKessfuBtn.setTitleColor(UIColor.white, for: .normal)
        jqfxhKessfuBtn.titleLabel?.font = UIFont.jqfxhRegular14
        jqfxhKessfuBtn.addTarget(self, action: #selector(jqfxhKessfuBtnClick), for: .touchUpInside)
        return jqfxhKessfuBtn
    }()
    
    
    lazy var jqfxhBgnnImage : UIImageView = {
        let jqfxhBgnnImage = UIImageView(image: UIImage(named: "jqfxh_home_top"))
        jqfxhBgnnImage.isUserInteractionEnabled = true
        return jqfxhBgnnImage
    }()
    
    
    lazy var jafxhEdurrCardImg : UIImageView = {
        let jafxhEdurrCardImg = UIImageView()
        jafxhEdurrCardImg.image = UIImage(named: "jqfxh_m_card")
        jafxhEdurrCardImg.isUserInteractionEnabled = true
        return jafxhEdurrCardImg
    }()
    
    lazy var jqfxhYugussCountTitle : UILabel = {
        let jqfxhYugussCountTitle = UILabel()
        jqfxhYugussCountTitle.font = UIFont.jqfxhRegular14
        jqfxhYugussCountTitle.textColor = UIColor.black
        jqfxhYugussCountTitle.text = "最高可担保额度（元）"
        return jqfxhYugussCountTitle
    }()
    
    
    lazy var jqfxhNavSubqqTitleLabel : UILabel = {
        let jqfxhNavSubqqTitleLabel = UILabel()
        jqfxhNavSubqqTitleLabel.font = UIFont.jqfxhRegular12
        jqfxhNavSubqqTitleLabel.textColor = UIColor.white
        jqfxhNavSubqqTitleLabel.text = "欢迎您的到来"
        return jqfxhNavSubqqTitleLabel
    }()
    
    
    
    lazy var jqfxhListuuBg : UIView = {
        let jqfxhListuuBg = UIView()
        jqfxhListuuBg.backgroundColor = UIColor.white
        jqfxhListuuBg.layer.cornerRadius = 12
        jqfxhListuuBg.layer.masksToBounds = true
        return jqfxhListuuBg
    }()
    
    lazy var jqfxhMyGongvvTitleLabel : UILabel = {
        let jqfxhMyGongvvTitleLabel = UILabel()
        jqfxhMyGongvvTitleLabel.font = UIFont.jqfxhRegular16
        jqfxhMyGongvvTitleLabel.textColor = UIColor.black
        jqfxhMyGongvvTitleLabel.text = "我的功能"
        return jqfxhMyGongvvTitleLabel
    }()
    
    lazy var jqfxhCountTttitle : UILabel = {
        let jqfxhCountTttitle = UILabel()
        jqfxhCountTttitle.font = UIFont.jqfxhRegular40
        jqfxhCountTttitle.textColor = UIColor.black
        jqfxhCountTttitle.text = "200,000"
        return jqfxhCountTttitle
    }()
   
    
    lazy var jqfxhBeianwwLabel : UILabel = {
        let jqfxhBeianwwLabel = UILabel()
        jqfxhBeianwwLabel.text = JQFXHCompanyMessage.jqfxhBeian
        jqfxhBeianwwLabel.font = UIFont.jqfxhRegular12
        jqfxhBeianwwLabel.textColor = UIColor.jqfxhTextLightaaGray
        return jqfxhBeianwwLabel
    }()

}


